package ru.ncedu.java.vlku.hrs.uil.cmd;

import ru.ncedu.java.vlku.hrs.bll.HRSManager;
import ru.ncedu.java.vlku.hrs.bll.HRSManagerFactory;
import ru.ncedu.java.vlku.hrs.model.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CreateBill implements Command {
    // <cargo_id> <tariff_id> <price> <quantity>
    private void executeSubCmd( String[] args ) {
        if (args.length != 4)
            throw new IllegalArgumentException();
        Long cargo_id = Long.parseLong(args[0]);
        Long tariff_id = Long.parseLong(args[1]);
        Long price = Long.parseLong(args[2]);
        Long quantity = Long.parseLong(args[3]);
        HRSManager manager = HRSManagerFactory.getInstance().getHRSManager();
        Cargo cargo = manager.getCargoById(cargo_id);
        Tariff tariff = manager.getTariffById(tariff_id);
        BillCargo bc = new BillCargo(cargo, tariff, price, quantity);
        manager.createBillCargo(bc);
    }
    // create bill <cust_acc_id> <shop_id> <date: dd.mm.yyyy>
    @Override
    public void execute( String[] args ) {
        if (args.length != 5)
            throw new IllegalArgumentException();
        Long cust_acc_id = Long.parseLong(args[2]);
        Long shop_id = Long.parseLong(args[3]);
        SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
        Date date = null;
        try {
            date = sdf.parse(args[4]);
        } catch ( ParseException e ) {
            throw new IllegalArgumentException("wrong date format");
        }
        HRSManager manager = HRSManagerFactory.getInstance().getHRSManager();
        CustomerAccount ca = manager.getCustomerAccountById(cust_acc_id);
        Shop shop = manager.getShopById(shop_id);
        Bill bill = new Bill(shop, ca, date);
        manager.createBill(bill);
        System.out.println("Input cargos in bill (<cargo_id> <tariff_id> <price> <quantity>). Enter 'q' to finish");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        boolean run_flag = true;
        while (run_flag) {
            System.out.print(">>>>>>");
            try {
                str = br.readLine();
                if (str.equals("q"))
                    run_flag = false;
                else
                    executeSubCmd(str.split(" "));
            } catch ( IllegalArgumentException e ) {
                System.err.println("Wrong format");
            } catch ( Exception e ) {
                System.err.println("Something wrong...");
                return;
            }
        }
    }
}
